#pragma once
#include "Command.hpp"
#include "InetArr.hpp"
#include "Pthread.hpp"
#include"Log.hpp"



using namespace PthreadModule;




class Client
{
private:
    // 默认执行函数
    void DefaultRoute(void)
    {
        while (true)
        {
            // 接收回显消息
            struct sockaddr_in recv_addr;
            socklen_t addr_len = sizeof(recv_addr);
            char buffer[1024];
            // 阻塞接受
            int n = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, CONV(&recv_addr), &addr_len);
            buffer[n] = 0;
            if (n == -1)
            {
                perror("recvfrom error");
                continue;
            }
            //std::cout << buffer << std::endl;
            LOG(LogModule::LogLevel::INFOMATION) <<"群聊信息："<<buffer;
        }
    }

public:
    Client(std::string ip = gdefaultip, uint16_t port = gdefaultport) : _inetAddr(port, ip),
                                                                        _isrunning(false),
                                                                        _thread([this]()
                                                                                { this->DefaultRoute(); })
    {
    }

    void InitClient()
    {
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            perror("socket error");
            return;
        }
        // 不需要自己绑定由OS自动绑定，避免多个应用冲突
        std::cout << "bind success" << std::endl;
    }
    void Start()
    {
        _isrunning = true;
        _thread.Start();

        std::string s="我来了！哈哈哈";
        ssize_t n = ::sendto(_sockfd, s.c_str(), s.size(), 0, _inetAddr.NetAddr(), _inetAddr.NetAddrLen());

        // 服务器死循环接受数据
        while (true)
        {
            std::cout << "Please Enter#";
            std::string line;
            getline(std::cin, line);

            ssize_t n = ::sendto(_sockfd, line.c_str(), line.size(), 0, _inetAddr.NetAddr(), _inetAddr.NetAddrLen());
            if (n == -1)
            {
                perror("sendto error");
                exit(1);
            }
        }
    }

    ~Client()
    {
        _thread.Stop();

        std::string s="我走了！";
        ssize_t n = ::sendto(_sockfd, s.c_str(), s.size(), 0, _inetAddr.NetAddr(), _inetAddr.NetAddrLen());

        if (_isrunning)
            ::close(_sockfd);
    }

private:
    int _sockfd;
    bool _isrunning; // 客户端运行状态
    InetAddr _inetAddr;
    Pthread _thread; // 执行多线程
};
